<?php
/**
 * Created by PhpStorm.
 * User:lyq
 * Date: 2018/8/25
 * Time: 17:08
 */

namespace app\admin\controller;

use app\admin\model\Wallet;
use app\common\model\UserBackstage;
use think\Exception;
use think\Db;
use think\Session;

class User extends Common
{
    public function index(){
        //标题
        $this->templateTitle("会员列表");
        $this->assign('duties_list',$this->get_duties_list());
        $this->assign('industry_list',$this->get_industry_list());
        $this->assign('identity_list',get_identity('',2));
        $where['us.id'] = ['gt',0] ;

        //搜索条件-手机
        $mobile = request()->param("mobile");
        $this->assign("mobile", $mobile);
        if ($mobile)
        {
            $where["us.mobile"] = $mobile;
        }
        //搜索条件-姓名
        $real_name = request()->param("real_name");
        $this->assign("real_name", $real_name);
        if ($real_name)
        {
            $where["us.real_name"] = $real_name;
        }
        //搜索条件-商会
        $bussiness_name = request()->param("bussiness_name");
        $this->assign("bussiness_name", $bussiness_name);
        if ($bussiness_name)
        {
            $where["bb.title|bb.id"] = $bussiness_name;

        }
        //搜索条件-组织结构
        $department_name = request()->param("department_name");
        $this->assign("department_name", $department_name);
        if ($department_name)
        {
            $where["de.title|de.id"] = $department_name;

        }
        //搜索条件-职务
        $duties_id= request()->param("duties_id");
        $this->assign("duties_id", $duties_id);
        if ($duties_id)
        {
            $where["du.id"] = $duties_id;
        }

        //搜索条件-行业
        $industry_id= request()->param("industry_id");
        $this->assign("industry_id", $industry_id);
        if ($industry_id)
        {
            $where["in.id"] = $industry_id;
        }

        //搜索条件-身份
        $identity_id = request()->param('identity_id');
        $this->assign('identity_id',$identity_id);
        if ($identity_id)
        {
            $where['us.identity'] = $identity_id;
        }
        //搜索条件-注册时间
        if (request()->has("time_range"))
        {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            //模板渲染值
            $this->assign("range_start", ["time_range" => $timeRange[0]]);
            $this->assign("range_end", ["time_range" => $timeRange[1]]);

            $where['us.create_time'] = [
                ["EGT", strtotime($timeRange[0] . " 00:00:00")],
                ["ELT", strtotime($timeRange[1] . " 23:59:59")]
            ];

        }
        else
        {
            //模板渲染值
            $this->assign("range_start", ["time_range" => '1970-01-01']);
            $this->assign("range_end", ["time_range" => date("Y-m-d")]);
        }

        //获取所有用户
        $list = Db::name("user")
            ->alias("us")
            ->join("__BUSSINESS__ bb", "us.bussiness_id=bb.id",'LEFT')
            ->join("__DEPARTMENT__ de", "us.department_id=de.id",'LEFT')
            ->join("__DUTIES__ du", "us.duties_id=du.id",'LEFT')
            ->join("__INDUSTRY__ in", "us.industry_id=in.id",'LEFT')
            ->where($where)
            ->order("us.create_time DESC")
            ->field('us.*,bb.title as bussiness_name,de.title as department_name,du.title as duties_name,in.title as industry_name')
            ->paginate(10);

        $this->assign("list", $list);
        $list = $list->toArray()['data'];
        $mobile_arr = array_column($list, 'mobile');
        $result = Wallet::someUser($mobile_arr);
        if($result['error_code']==0){
            $this->assign('hlarr',$result['result']);
        }else{
            $this->assign('hlarr',[]);
        }
        return $this->fetch();
    }

    public function invite(){
        $this->layoutModal();

        $this->assign('duties_list',$this->get_duties_list());
        $this->assign('industry_list',$this->get_industry_list());
        $this->assign('identity_list',get_identity('',2));

        $id = request()->param('id');
        $where['us.id'] = ['gt',0] ;
        $where['us.parent_id'] = $id;

        //搜索条件-手机
        $mobile = request()->param("mobile");
        $this->assign("mobile", $mobile);
        if ($mobile)
        {
            $where["us.mobile"] = $mobile;
        }
        //搜索条件-姓名
        $real_name = request()->param("real_name");
        $this->assign("real_name", $real_name);
        if ($real_name)
        {
            $where["us.real_name"] = $real_name;
        }
        //搜索条件-商会
        $bussiness_name = request()->param("bussiness_name");
        $this->assign("bussiness_name", $bussiness_name);
        if ($bussiness_name)
        {
            $where["bb.title|bb.id"] = $bussiness_name;

        }
        //搜索条件-组织结构
        $department_name = request()->param("department_name");
        $this->assign("department_name", $department_name);
        if ($department_name)
        {
            $where["de.title|de.id"] = $department_name;

        }
        //搜索条件-职务
        $duties_id= request()->param("duties_id");
        $this->assign("duties_id", $duties_id);
        if ($duties_id)
        {
            $where["du.id"] = $duties_id;
        }

        //搜索条件-行业
        $industry_id= request()->param("industry_id");
        $this->assign("industry_id", $industry_id);
        if ($industry_id)
        {
            $where["in.id"] = $industry_id;
        }

        //搜索条件-身份
        $identity_id = request()->param('identity_id');
        $this->assign('identity_id',$identity_id);
        if ($identity_id)
        {
            $where['us.identity'] = $identity_id;
        }
        //搜索条件-注册时间
        if (request()->has("time_range"))
        {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            //模板渲染值
            $this->assign("range_start", ["time_range" => $timeRange[0]]);
            $this->assign("range_end", ["time_range" => $timeRange[1]]);

            $where['us.create_time'] = [
                ["EGT", strtotime($timeRange[0] . " 00:00:00")],
                ["ELT", strtotime($timeRange[1] . " 23:59:59")]
            ];

        }
        else
        {
            //模板渲染值
            $this->assign("range_start", ["time_range" => '1970-01-01']);
            $this->assign("range_end", ["time_range" => date("Y-m-d")]);
        }

        //获取所有用户
        $list = Db::name("user")
            ->alias("us")
            ->join("__BUSSINESS__ bb", "us.bussiness_id=bb.id",'LEFT')
            ->join("__DEPARTMENT__ de", "us.department_id=de.id",'LEFT')
            ->join("__DUTIES__ du", "us.duties_id=du.id",'LEFT')
            ->join("__INDUSTRY__ in", "us.industry_id=in.id",'LEFT')
            ->where($where)
            ->order("us.create_time DESC")
            ->field('us.*,bb.title as bussiness_name,de.title as department_name,du.title as duties_name,in.title as industry_name')
            ->paginate(10);

        $this->assign("list", $list);
        $list = $list->toArray()['data'];
        $mobile_arr = array_column($list, 'mobile');
        $result = Wallet::someUser($mobile_arr);
        if($result['error_code']==0){
            $this->assign('hlarr',$result['result']);
        }else{
            $this->assign('hlarr',[]);
        }
        return $this->fetch();
    }

    private function get_duties_list(){
        $list = Db::name("duties")
            ->order('level asc,display_order desc')
            ->field("id,title")
            ->select();

        if ($list)
        {
            return $list;
        }
        else
        {
            return array();
        }
    }

    private function get_industry_list(){
        $list = Db::name("industry")
            ->where("is_visible", 1)
            ->order('display_order desc,create_time desc')
            ->field("id,title")
            ->select();

        if ($list)
        {
            return $list;
        }
        else
        {
            return array();
        }
    }

    public function activate(){
        if(request()->isAjax()){
            $id = request()->param('id');
            $user = Db::name('user')->where('id',$id)->find();
            if(!$user){
                $this->save_admin_log($id,'激活会员失败-未查询到此会员');
                return $this->ajaxError('未查询到此会员');
            }
            if($user['identity']!=1){
                $this->save_admin_log($id,'激活会员失败-重复激活');
                return $this->ajaxError('此会员已经激活，禁止重复激活');
            }
            if($user['in_blacklist']!=0){
                $this->save_admin_log($id,'激活会员失败-会员已拉黑无法激活');
                return $this->ajaxError('此会员已被加入黑名单，无法激活');
            }

            $rate = Db::name('rate')->where('id',1)->find();
            if($rate['activate_give']>0){
                $wallet = Wallet::oneUser($user['mobile']);
                if($wallet['error_code']!=0){
                    $this->save_admin_log($id,'激活会员失败-会员未开通钱包，无法赠送H链资产');
                    return $this->ajaxError('此会员未开通钱包，无法赠送H链资产，请先通知会员开通钱包再进行激活操作');
                }
            }

            $save = Db::name('user')
                ->where('id',$id)
                ->update(['identity'=>2]);
            if($save){
                if($rate['activate_give']>0){
                    Wallet::addDelCoin($user['mobile'],$rate['activate_give'],1,'后台激活会员，平台赠送');
                }
                if($rate['activate_reward']>0 && !empty($user['parent_id'])){
                    //邀请激活奖励大于0 并 被激活会员存在上级ID
                    $parent = Db::name('user')
                        ->where('id',$user['parent_id'])
                        ->find();
                    if($parent){
                        Wallet::addDelCoin($parent['mobile'],$rate['activate_reward'],1,'邀请会员'.$user['mobile'].'激活成功，平台奖励');
                    }
                }

                $this->save_admin_log($id,'激活会员成功');
                return $this->ajaxSuccess('会员激活成功');
            }else{
                $this->save_admin_log($id,'激活会员失败-服务器繁忙');
                return $this->ajaxError('服务器繁忙，请稍后再试');
            }
        }
    }
    private function save_admin_log($uid,$content,$money=''){
        $admin = Session::get('H_ADMIN_LOGIN_USER');
        $data = [
            'admin_id'=>$admin['id'],
            'user_id'=>$uid,
            'content'=>$content,
            'money'=>$money,
            'create_time'=>time(),
            'user_name'=>$admin['username']
        ];
        Db::name('admin_log')->insert($data);
    }

    public function blacklist()
    {
        if (request()->isAjax())
        {
            $id = request()->param("id");
            //状态
            $status = request()->param("status");

            if(!in_array($status,[0,1])){
                return $this->ajaxError('操作参数有误');
            }
            try
            {
                $s = Db::name("user")
                    ->where("id", $id)
                    ->update(array(
                        "in_blacklist" => $status,
                        "update_time" => now_datetime(),
                    ));
                if($s){
                    if($status==1){
                        //加入黑名单
                        $union = Db::name('union')
                            ->where('uid',$id)
                            ->find();
                        if($union){
                            Db::name('union')
                                ->where('uid',$id)
                                ->update([
                                    "in_blacklist" => $status,
                                    "update_time" => now_datetime(),
                                ]);
                            Db::name('union_discount')
                                ->where('union_id',$union['id'])
                                ->delete();
                        }
                        return $this->ajaxSuccess('拉黑操作成功');
                    }else{
                        return $this->ajaxSuccess('取消拉黑操作成功，若绑定了联盟商请前往手动取消联盟商拉黑');
                    }

                }else{
                    return $this->ajaxError('服务器繁忙，请稍后再试');
                }
            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }

        }
    }

    public function add(){

        if(request()->isGet()){
            $this->layoutModal();
            //职务
            $this->assign('duties_list',$this->get_duties_list());
            //行业
            $this->assign('industry_list',$this->get_industry_list());
            return $this->fetch();
        }

        if(request()->isAjax()){
            $bussiness_id = intval(request()->param('bussiness_id'));
            $department_id = intval(request()->param('department_id'));
            $duties_id = intval(request()->param('duties_id'));
            $industry_id = intval(request()->param('industry_id'));
            $mobile = trim(request()->param('mobile'));
            $real_name = trim(request()->param('real_name'));
            $password = trim(request()->param('password'));
            $email = trim(request()->param('email'));
            $avatar = trim(request()->param('avatar'));
            $abstract = trim(request()->param('abstract'));
            $server = trim(request()->param('server'));
            $honor = trim(request()->param('honor'));

            $result = UserBackstage::register($bussiness_id,$department_id,$duties_id,$industry_id,$mobile,$real_name,$password,$email,$avatar,$abstract,$server,$honor);

            if($result['status']==0){
                return $this->ajaxSuccess($result['info'],$result['data']);
            }else{
                return $this->ajaxError($result['info'],$result['data']);
            }
        }
    }

    public function edit(){
        $id = request()->param('id');
        if(request()->isGet()){
            $this->layoutModal();
            $info = Db::name('user')->where('id',$id)->find();
            $this->assign('info',$info);

            //数据处理
            //商会
            $this->assign('bussiness_id',$info['bussiness_id']);
            //组织部门
            $this->assign('department_id',$info['department_id']);
            //职务
            $this->assign('duties_list',$this->get_duties_list());
            //行业
            $this->assign('industry_list',$this->get_industry_list());
            //头像
            $this->assign("single_image", array("avatar"=>$info["avatar"]));

            return $this->fetch();
        }

        if(request()->isAjax()){
            $where['id'] = $id;
            $bussiness_id = intval(request()->param('bussiness_id'));
            $department_id = intval(request()->param('department_id'));
            $duties_id = intval(request()->param('duties_id'));
            $industry_id = intval(request()->param('industry_id'));
            $mobile = trim(request()->param('mobile'));
            $real_name = trim(request()->param('real_name'));
            $password = trim(request()->param('password'));
            $email = trim(request()->param('email'));
            $avatar = trim(request()->param('avatar'));
            $abstract = trim(request()->param('abstract'));
            $server = trim(request()->param('server'));
            $honor = trim(request()->param('honor'));

            $result = UserBackstage::edit($where,$id,$bussiness_id,$department_id,$duties_id,$industry_id,$mobile,$real_name,$password,$email,$avatar,$abstract,$server,$honor);

            if($result['status']==0){
                return $this->ajaxSuccess($result['info'],$result['data']);
            }else{
                return $this->ajaxError($result['info'],$result['data']);
            }
        }
    }

    public function hlHistory()
    {
        $id = request()->param('id');
        $page = request()->param('page');
        $page = empty($page) ? 1 : $page;

        if(request()->isGet()) {
            $this->layoutModal();

            $user = Db::name('user')->where('id',$id)->field('mobile')->find();
            if(!$user||empty($user['mobile'])){
                $this->error('此会员参数有误');
            }

            $result = Wallet::hlHistory($user['mobile'],10,$page);

            if($result['error_code']==0){
                //list
                $this->assign('list',$result['result']['codes']);
                //page
                $html = '<ul class="pagination">';
                for($i=1;$i<=$result['result']['pagenum'];$i++){
                    $html .= '<li><a href="/User/hlHistory.html?id='.$id.'&page='.$i.'">'.$i.'</a></li>';
                }
                $html .= '</ul>';
                $this->assign('page',$html);
            }else{
                $this->assign('list',[]);
                $this->assign('page','');
            }
            return $this->fetch();
        }
    }

    public function import(){
        ob_clean();
        header("Content-type:text/html;Charset=utf-8");

        if(request()->isGet()){
            //删除无用excel
            removeOldExcel();
            $this->layoutModal();
            return $this->fetch();
        }

        if(request()->isAjax()){
            ini_set('memory_limit','100M');    // 临时设置最大内存占用为100M
            set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期

            $file_path = request()->param('excel_path'); //上传后的EXCEL路径
            if(empty($file_path)){
                return $this->ajaxError('请上传excel文件');
            }
            try{
                $file_path = '.'.$file_path;
                if (!file_exists($file_path)) {
                    return $this->ajaxError('excel文件未找到');
                }
                $extension_arr = explode('.',$file_path);
                $extension = array_pop($extension_arr);

                switch ($extension) {
                    case 'xls':
                        $type = 'Excel5';
                        break;
                    case 'xlsx':
                        $type = 'Excel2007';
                        break;
                }

                $objReader = \PHPExcel_IOFactory::createReader($type);

                $obj_PHPExcel =$objReader->load($file_path);  //加载文件内容,编码utf-8
                $sheet = $obj_PHPExcel->getSheet(0); //激活当前的表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumn = $sheet->getHighestColumn(); // 取得总列数
                if($highestColumn!='J'){
                    return $this->ajaxError('请使用下载的会员导入模板进行导入操作');
                }
                $highestRow--;
                if($highestRow>config('max_excle_row')){
                    return $this->ajaxError('导入会员数据条数请少于'.config('max_excle_row').'条');
                }

                if($highestRow<=0){
                    return $this->ajaxError('excel文件中数据为空');
                }

                $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
                array_shift($excel_array);  //删除第一个数组(标题);
                $data = [
                    'all_num'=>$highestRow,
                    'success_num'=>0,
                    'success_arr'=>[],
                    'fail_num'=>0,
                    'fail_arr'=>[]
                ];
                $nums = 1;
                foreach ($excel_array as $item){

                    $password = substr($item[4],5);
                    $res = UserBackstage::register($item[0],$item[1],$item[2],$item[3],$item[4],$item[5],$password,$item[6],'',$item[7],$item[8],$item[9]);
                    if($res['status']==0){
                        //导入成功
                        $data['success_num'] = $data['success_num']+1;
                        $data['success_arr'][] = $item[4].'-'.$item[5].' 导入成功：登录密码为手机号后6位';
                    }else{
                        //导入失败
                        $data['fail_num'] = $data['fail_num']+1;
                        $data['fail_arr'][] = $item[4].'-'.$item[5].' 导入失败：'.$res['info'];
                    }
                    if($nums%100==0){
                        session_write_close();
                        sleep(1);
                    }
                    $nums++;
                }
                return $this->ajaxSuccess('导入完成',$data);
            }catch (Exception $exception){
                return $this->ajaxError($exception->getMessage());
            }

        }
    }

    /**
     *下载excel模板
     */
    public function down_excel(){
        $file_path = './static/excel/admin_user_model.xlsx';
        $res = downloadFile($file_path,'后台会员批量导入EXCEL模板');
        if($res['status']==1){
            $this->error($res['info']);
        }
    }
}

